import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:viser_remit/core/helper/string_format_helper.dart';
import 'package:get/get.dart';
import 'package:viser_remit/data/controller/home/home_controller.dart';
import 'package:viser_remit/data/controller/send_money/send_money_controller.dart';

import '../../../core/route/route.dart';
import '../../../core/utils/my_strings.dart';
import '../../../view/components/snack_bar/show_custom_snackbar.dart';
import '../../model/deposit/deposit_insert_response_model.dart';
import '../../model/deposit/deposit_method_response_model.dart';
import '../../model/global/response_model/response_model.dart';
import '../../repo/deposit/deposit_repo.dart';

class AddNewDepositController extends GetxController {
  DepositRepo depositRepo;
  AddNewDepositController({required this.depositRepo});

  HomeController homeController = Get.find();
  bool isLoading = true;

  String selectedValue = "";
  String depositLimit = "";

  String gateWayCharge = "";
  String payableIncludeChage = "";
  String conversionRate = '';
  String conversionTotalAmount = '';

  String payable = "";

  String currency = '';

  List<Methods> methodList = [];
  Methods? paymentMethod = Methods(name: MyStrings.selectOne, id: -1);

  TextEditingController amountController = TextEditingController();
  TextEditingController amountInBaseCurrencyController = TextEditingController();

  double rate = 1;
  double mainAmount = 0;
  double mainBaseAmount = 0;

  setPaymentMethod(Methods? method) {
    String amt = amountController.text.toString();
    mainAmount = amt.isEmpty ? 0 : double.tryParse(amt) ?? 0;
    String baseAmount = amountInBaseCurrencyController.text.toString();
    mainBaseAmount = baseAmount.isEmpty ? 0 : double.tryParse(baseAmount) ?? 0;
    paymentMethod = method;

    depositLimit = '${Converter.formatNumber(method?.minAmount?.toString() ?? '-1')} - ${Converter.formatNumber(method?.maxAmount?.toString() ?? '-1')} $currency';
    changeInfoWidgetValue(
      mainAmount,
      mainBaseAmount,
    );
    update();
  }

  double calculatePercentage(double number, double percentage) {
    return (percentage / 100) * number;
  }

  Future<void> getDepositMethod(String amountValue, String payableAmount, String senderCountryRateForBase) async {
    currency = homeController.selectedSendCountry.currency!;
    methodList.clear();
    methodList.add(paymentMethod!);

    amountController.text = amountValue;
    amountInBaseCurrencyController.text = payableAmount;

    ResponseModel responseModel = await depositRepo.getDepositMethods();

    if (responseModel.statusCode == 200) {
      DepositMethodResponseModel methodsModel = DepositMethodResponseModel.fromJson(jsonDecode(responseModel.responseJson));

      if (methodsModel.message != null && methodsModel.message!.success != null) {
        List<Methods>? tempList = methodsModel.data?.methods;
        if (tempList != null && tempList.isNotEmpty) {
          methodList.addAll(tempList);
        }
      }
    } else {
      CustomSnackBar.error(errorList: [responseModel.message]);
      return;
    }

    isLoading = false;
    update();
  }

  bool submitLoading = false;
  Future<void> submitDeposit() async {
    if (paymentMethod?.id.toString() == '-1') {
      CustomSnackBar.error(errorList: [MyStrings.selectPaymentMethod]);
      return;
    }

    String amount = amountController.text.toString();
    if (amount.isEmpty) {
      CustomSnackBar.error(errorList: [MyStrings.enterAmount]);
      return;
    }

    submitLoading = true;
    update();

    ResponseModel responseModel = await depositRepo.insertDeposit(amount: amount, methodCode: paymentMethod?.methodCode ?? "", currency: paymentMethod?.currency ?? "", trx: Get.find<SendMoneyController>().trxNumber);

    if (responseModel.statusCode == 200) {
      DepositInsertResponseModel insertResponseModel = DepositInsertResponseModel.fromJson(jsonDecode(responseModel.responseJson));

      if (insertResponseModel.status.toString().toLowerCase() == "success") {
        showWebView(insertResponseModel.data?.redirectUrl ?? "");
      } else {
        CustomSnackBar.error(errorList: insertResponseModel.message?.error ?? [MyStrings.somethingWentWrong]);
      }
    } else {
      CustomSnackBar.error(
        errorList: [responseModel.message],
      );
    }

    submitLoading = false;
    update();
  }

  void changeInfoWidgetValue(double amount, double mainBaseAmount) {
    String baseCurrency = depositRepo.apiClient.getCurrencyOrUsername(isCurrency: true);

    if (paymentMethod?.id.toString() == '-1') {
      return;
    }

    mainAmount = amount;
    mainBaseAmount = mainBaseAmount;

    double percent = double.tryParse(paymentMethod?.percentCharge ?? '0') ?? 0;

    double fixedCharge = double.tryParse(paymentMethod?.fixedCharge ?? '0') ?? 0;

    rate = double.tryParse(paymentMethod?.rate ?? '0') ?? 0;

    double percentCharge = (mainBaseAmount * percent) / 100;

    double totalCharge = percentCharge + fixedCharge;

    double totalPayableIncludeCharge = totalCharge + mainBaseAmount;
    double totalConvertionAmountIncludeCharge = totalPayableIncludeCharge * rate;

    //GateWay Charge

    gateWayCharge = '${Converter.formatNumber('$totalCharge')} $baseCurrency';
    //Payable Include charge
    payableIncludeChage = '${Converter.formatNumber('$totalPayableIncludeCharge')} $baseCurrency';

    //Convertion Rate
    conversionRate = '1 $baseCurrency = $rate ${paymentMethod?.currency ?? ''}';

    //Convertion Total Amount
    conversionTotalAmount = "${Converter.formatNumber('$totalConvertionAmountIncludeCharge')} ${paymentMethod?.currency ?? ''}";

    update();
    return;
  }

  void clearData() {
    depositLimit = '';
    gateWayCharge = '';
    payableIncludeChage = '';
    amountController.text = '';
    amountInBaseCurrencyController.text = '';
    isLoading = false;
    methodList.clear();
  }

  bool isShowRate() {
    if (rate > 1 && currency.toLowerCase() != paymentMethod?.currency?.toLowerCase()) {
      return true;
    } else {
      return false;
    }
  }

  void showWebView(String redirectUrl) {
    Get.offAndToNamed(RouteHelper.depositWebViewScreen, arguments: redirectUrl);
  }
}
